package com.ice.netty.protobuf.handle;

import com.google.protobuf.InvalidProtocolBufferException;
import com.ice.netty.modbus.data.DeviceInfoData;
import com.ice.netty.modbus.data.MsgBaseData;
import com.ice.netty.modbus.data.ScanCodeData;
import com.ice.netty.protobuf.msg.ProtoMsg;
import com.ice.netty.protobuf.server.ProtoServer;
import com.ice.remoting.common.CommonConstant;
import com.ice.remoting.common.RemotingHelper;
import com.ice.remoting.data.RemotingCommand;
import com.ice.remoting.netty.NettyRequestProcessor;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ProtoDefaultProcess implements NettyRequestProcessor {

    private ProtoServer protoServer;

    public ProtoDefaultProcess(ProtoServer protoServer) {
        this.protoServer = protoServer;
    }

    @Override
    public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws InvalidProtocolBufferException {
        ProtoMsg.Message outmsg = ProtoMsg.Message.parseFrom(request.getBody());
        if (ProtoMsg.HeadType.HERART == outmsg.getType()) {
            log.info("处理心跳");
            ProtoMsg.HeartBeatReq heartBeatReq = outmsg.getHeartBeatReq();
            handleHeartBeant(ctx, heartBeatReq);
        }
        if (ProtoMsg.HeadType.DEVICE == outmsg.getType()) {
            log.info("处理设备编号");
            ProtoMsg.DeviceInfoReq deviceInfoReq = outmsg.getDeviceInfoReq();
            handleDevice(ctx, deviceInfoReq);
        }
        if (ProtoMsg.HeadType.SCANCODERES == outmsg.getType()) {
            log.info("处理扫码状态");
            ProtoMsg.ScanCodeRes scanCodeRes = outmsg.getScanCodeRes();
            handleScanCode(ctx, scanCodeRes);
        }
        return null;
    }

    /**
     * 处理心跳
     *
     * @Author wangwei
     * @Date 2024/1/22
     */
    private RemotingCommand handleHeartBeant(ChannelHandlerContext ctx, ProtoMsg.HeartBeatReq heartBeatReq) {
        final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
        protoServer.getDeviceManager().updateBrokerInfoUpdateTimestamp(remoteAddress);
        return null;
    }

    private RemotingCommand handleDevice(ChannelHandlerContext cxt, ProtoMsg.DeviceInfoReq deviceInfoReq) {
        log.info("设备编码：{}", deviceInfoReq.getDeviceNo());
        // 设置唯一编号
        this.protoServer.setCustomerUniqueIdentity(cxt.channel(), deviceInfoReq.getDeviceNo());
        // 设置设备编号
        cxt.channel().attr(AttributeKey.valueOf(CommonConstant.DEVICE_NO)).setIfAbsent(deviceInfoReq.getDeviceNo());
        return null;
    }

    private RemotingCommand handleScanCode(ChannelHandlerContext cxt, ProtoMsg.ScanCodeRes scanCodeRes) {
        log.info("开锁状态：{}", scanCodeRes.getScanStatus());
        return null;
    }
}
